package com.fei.wechat.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fei.wechat.admin.aspect.annotation.AnnoOperateLog;
import com.fei.wechat.common.constant.Constants;
import com.fei.wechat.common.constant.OperateLogConstant;
import com.fei.wechat.common.constant.OperateLogContentTemplate;
import com.fei.wechat.common.model.vo.RespVo;
import com.fei.wechat.middlewar.api.admin.IAuthorityService;
import com.fei.wechat.middlewar.api.admin.IOperateLogService;
import com.fei.wechat.middlewar.api.admin.IOrgaService;
import com.fei.wechat.middlewar.api.admin.IRoleService;
import com.fei.wechat.middlewar.api.admin.IUserService;
import com.fei.wechat.middlewar.mode.bo.admin.LoginBo;
import com.fei.wechat.middlewar.mode.entity.admin.Orga;
import com.fei.wechat.middlewar.mode.entity.admin.User;
import com.fei.wechat.middlewar.mode.vo.admin.CurrentUser;

/**
 * 描述: 登录控制层
 * 版权: Copyright (c) 2018 
 * 公司: 飞翔科技 
 * 作者: 张进飞 
 * 版本: 1.0 
 * 创建日期: 2018年3月5日 
 * 创建时间: 下午11:09:46
 */
@Controller
@RequestMapping("/admin/login")
public class LoginController extends BaseController
{
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IOrgaService orgaService;
    
    @Autowired
    private IRoleService roleService;
    
    @Autowired
    private IAuthorityService authorityService;
    
    @Autowired
    private IOperateLogService operateLogService;
    
    /**
     * 描述：index页面
     * 作者：张进飞
     * 时间：2018年3月10日 上午11:47:47
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        return mav;
    }
    
    /**
     * 描述：登录提交方法
     * 作者：张进飞
     * 时间：2018年4月22日 下午8:30:51
     * @return
     */
    @AnnoOperateLog(moduleName = OperateLogConstant.MODULE_INDEX, function = OperateLogConstant.FUNCTION_PAGE_LOGIN, operateType = OperateLogConstant.OPERATE_ID_LOGIN, operateContentTemplate = OperateLogContentTemplate.LOGIN_USER)
    @RequestMapping(value = "/loginSubmit")
    @ResponseBody
    public RespVo loginSubmit(LoginBo loginBo, HttpServletRequest request)
    {
        RespVo respVo = new RespVo();
        if (StringUtils.isBlank(loginBo.getLoginName()) || StringUtils.isBlank(loginBo.getPassword()))
        {
            respVo.setCode(RespVo.VALIDATE_ERROR);
            respVo.setMessage("参数错误");
            return respVo;
        }
        //登录名去除空格
        String loginName = "";
        if (StringUtils.isNotEmpty(loginBo.getLoginName()))
        {
            loginName = loginBo.getLoginName().trim();
        }
        //String loginIP = getLoginIP(request);
        User user = userService.queryUserByLoginName(loginName);
        if (user == null)
        {
            respVo.setCode(RespVo.VALIDATE_ERROR);
            respVo.setMessage("用户不存在");
            return respVo;
        }
        //校验密码是否正确
        if (!user.getPassword().equals(loginBo.getPassword()))
        {
            respVo.setCode(RespVo.VALIDATE_ERROR);
            respVo.setMessage("用户名或密码错误");
            return respVo;
        }
        if (user.getAvailable().intValue() == 0)
        {
            respVo.setCode(RespVo.VALIDATE_ERROR);
            respVo.setMessage("用户已被禁用，请联系系统管理员！");
            return respVo;
        }
        Object[] logArray = new Object[2];
        try
        {
            logArray[0] = loginName;
            Orga orga = orgaService.queryOrgaById(user.getOrgaId());
            CurrentUser currentUser = new CurrentUser();
            currentUser.setUser(user);
            currentUser.setOrga(orga);
            currentUser.setRoles(roleService.getRolesByUserId(user.getId()));
            currentUser.setAuthoritys(authorityService.queryAuthoritiesByRoles(currentUser.getRoles()));
            request.getSession().setAttribute(Constants.USER_LOGIN_FLAG, currentUser);
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("登录成功");
            logArray[1] = "成功";
        }
        catch (Exception e)
        {
            this.logger.error("登录异常：", e);
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("登录失败");
            logArray[1] = "成功";
        }
        //登录日志
        respVo.setLogArgs(logArray);
        return respVo;
    }
    
    /**
     * 描述：登出系统
     * 作者：张进飞
     * 时间：2018年7月7日 下午3:57:47
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/logOut")
    public ModelAndView logOut(HttpServletRequest request) throws Exception
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:/admin/login/index");
        CurrentUser currentUser = this.getCurrentUser(request);
        if (null != currentUser)
        {
            String loginName = currentUser.getUser().getLoginName();
            String operateIP = getLoginIP(request);
            Object[] objArray = new Object[2];
            objArray[0] = loginName;
            try
            {
                // 销毁当前用户登录session
                HttpSession session = request.getSession();// 获取当前用户session
                session.invalidate();// 销毁当前用户session会话
                
                objArray[1] = "成功";
                operateLogService.saveOperateLog(OperateLogConstant.MODULE_INDEX, OperateLogConstant.FUNCTION_LOGOUT, loginName, operateIP, OperateLogConstant.OPERATE_ID_CLOGIN,
                        OperateLogContentTemplate.CLOGIN_USER, objArray, null);
            }
            catch (Exception e)
            {
                objArray[1] = "失败";
                operateLogService.saveOperateLog(OperateLogConstant.MODULE_INDEX, OperateLogConstant.FUNCTION_LOGOUT, loginName, operateIP, OperateLogConstant.OPERATE_ID_CLOGIN,
                        OperateLogContentTemplate.CLOGIN_USER, objArray, null);
                logger.error("用户退出系统，异常：", e);
            }
        }
        return mav;
    }
}
